package com.example.commontest.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

/**
 * @Author huaiyu yin
 * @Date 2021/6/17 2:44 下午
 * @Version 1.0
 */
public class DingDingRobotUtil {
    private static final Logger logger = LoggerFactory.getLogger(DingDingRobotUtil.class);
    /**
     *
     * @param webhook
     * @param secret     安全设置 3选1【方式一，自定义关键词 】 【方式二，加签 ，创建机器人时选择加签 secret以SE开头】【方式三，IP地址（段）】
     * @param content    发送内容 注意带上关键词
     * @param isAtAll    通知所有人
     * @return
     */
    public static void sendMsg(String webhook, String secret, String content, boolean isAtAll) {
        try {
            //钉钉机器人地址（配置机器人的webhook）
            if (!StringUtils.isEmpty(secret)) {
                Long timestamp = System.currentTimeMillis();
                String sign = getSign(timestamp, secret);
                webhook = new StringBuilder(webhook)
                        .append("&timestamp=")
                        .append(timestamp)
                        .append("&sign=")
                        .append(sign)
                        .toString();
            }
            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, null);
            //推送消息（http请求）
            HttpClientUtil.postJsonData(webhook,reqStr);
        } catch (Exception e) {
            logger.info("发送群通知异常 异常原因：{}", e.getStackTrace());
        }
    }

    public static void sendMsg(String webhook, String secret, String content, List<String> mobileList) {
        try {
            //钉钉机器人地址（配置机器人的webhook）
            if (!StringUtils.isEmpty(secret)) {
                Long timestamp = System.currentTimeMillis();
                String sign = getSign(timestamp, secret);
                webhook = new StringBuilder(webhook)
                        .append("&timestamp=")
                        .append(timestamp)
                        .append("&sign=")
                        .append(sign)
                        .toString();
            }
            //是否通知所有人
            boolean isAtAll = false;
            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, mobileList);
            //推送消息（http请求）
            HttpClientUtil.postJsonData(webhook,reqStr);
        } catch (Exception e) {
            logger.info("发送群通知异常 异常原因：{}", e.getStackTrace());
        }
    }

    /**
     * 组装请求报文
     * 发送消息类型 text
     *
     * @param content
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("content", content);
        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        return JSONObject.toJSONString(reqMap);
    }

    /**
     *
     * 自定义机器人获取签名
     * 创建机器人时选择加签获取secret以xxxx开头
     *
     * @param timestamp
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    private static String getSign(Long timestamp, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        return sign;
    }

    public static void main(String[] args) {
        String webhook =  "自己的webhook";
        String secret = "SECxxxxx";
        String content = "老道提示: 优秀的一天！";
        List<String> mobileList = Lists.newArrayList();
        mobileList.add("18******");
//        DingDingRobotUtil.sendMsg(webhook,secret,content, mobileList);
        DingDingRobotUtil.sendMsg(webhook,secret,content, true);
    }
}
